package communication.server.vertx.service.impl;

import communication.common.business.base.FcrSocketAddress;
import communication.server.vertx.dao.DeviceInfoDao;
import communication.server.vertx.entity.DeviceInfo;
import communication.common.business.user.request.LoginRequest;
import communication.common.business.user.request.RegistryRequest;
import communication.common.business.user.response.UserLoggedInfo;
import communication.server.vertx.dao.UserInfoDao;
import communication.server.vertx.entity.UserInfo;
import communication.common.business.user.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * @author mac
 */
@Component
@Slf4j
@AllArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserInfoDao userInfoDao;

    private final DeviceInfoDao deviceInfoDao;

    @Override
    public Long registry(RegistryRequest request) throws Exception {
        UserInfo userInfo = userInfoDao.findByPhoneAndDeleteFlg(request.getPhone(),false);

        if(userInfo != null){
            throw new Exception("手机已注册");
        }

        userInfo = userInfoDao.findByAccountNameAndPassWdAndDeleteFlg(request.getAccountName(),request.getPassWord(),false);

        if(userInfo != null){
            throw new Exception("账户名称已存在");
        }

        // 注册用户信息
        userInfo = new UserInfo();
        userInfo.setAccountName(request.getAccountName());
        userInfo.setGender(request.getGender());
        userInfo.setPassWd(request.getPassWord());
        userInfo.setPhone(request.getPhone());

        userInfoDao.save(userInfo);

        return userInfo.getId();

    }

    @Override
    public UserLoggedInfo loginByAccountName(LoginRequest loginRequest, FcrSocketAddress remoteSocketAddress) throws Exception {
        // 查询用户信息
        UserInfo userInfo = userInfoDao.findByAccountNameAndPassWdAndDeleteFlg(loginRequest.getAccountName(), loginRequest.getPassWord(), false);
        if(userInfo == null){
            throw new Exception("用户名称或密码错误");
        }

        // 更新用户设想信息
        DeviceInfo deviceInfo = deviceInfoDao.getByUserId(userInfo.getId());
        if(deviceInfo == null){
            deviceInfo=DeviceInfo.builder().build();
        }
        deviceInfo.setUserId(userInfo.getId());
        deviceInfo.setNetAddress(remoteSocketAddress.getAddress());
        deviceInfo.setOnlineFlg(true);

        deviceInfoDao.save(deviceInfo);

        // todo: 生成cookie
        return UserLoggedInfo.builder()
                .userId(userInfo.getId())
                .cookie("cookie")
                .build();
    }
}
